import java.util.*;

/**
 * 675. 为高尔夫比赛砍树
 */
class Solution {
    int m, n;
    int[] dx = {-1, 1, 0, 0};
    int[] dy = {0, 0, -1, 1};
    public int cutOffTree(List<List<Integer>> forest) {
        m = forest.size();
        n = forest.get(0).size();
        //1、准备工作，确认砍树顺序
        List<int[]> trees = new ArrayList<>();
        //把forest的坐标存进trees中
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(forest.get(i).get(j) > 1) {
                    trees.add(new int[]{i, j});
                }
            }
        }
        //排序
        Collections.sort(trees, (a, b) ->{
            return forest.get(a[0]).get(a[1]) - forest.get(b[0]).get(b[1]);
        });
        //2、按顺序砍树，计算每一步的最短路径(边权为1的问题)
        int ret = 0;
        int curX = 0, curY = 0;
        for(int[] tree : trees) {
            int x = tree[0], y = tree[1];
            int step = bfs(forest, new int[]{curX, curY}, new int[]{x, y});
            if(step == -1) return -1;
            ret += step;
            curX = x; curY = y;
        }
        return ret;
    }

    public int bfs(List<List<Integer>> forest, int[] cur, int[] target) {
        if(cur[0] == target[0] && cur[1] == target[1]) return 0;

        boolean[][] vist = new boolean[m][n];
        Queue<int[]> q = new LinkedList<>();

        q.add(cur);
        vist[cur[0]][cur[1]] = true;

        int step = 0;
        while(!q.isEmpty()) {
            step++;
            int sz = q.size();
            while(sz-- != 0) {
                int[] tmp = q.poll();
                int a = tmp[0], b = tmp[1];
                for(int i = 0; i < 4; i++) {
                    int x = a + dx[i], y = b + dy[i];
                    if(x >= 0 && x < m && y >= 0 && y < n && !vist[x][y] && forest.get(x).get(y) != 0) {
                        if(forest.get(x).get(y) == forest.get(target[0]).get(target[1]))
                            return step;
                        q.add(new int[]{x, y});
                        vist[x][y] = true;
                    }
                }
            }
        }
        return -1;
    }
}